/**
 * Mock Utility
 * @author Wangtd
 */
const fs = require('fs');
const path = require('path');

module.exports = {
    find: function(list, predicate) {
        for (var index in list) {
            if (predicate(list[index], index)) {
                return list[index];
            }
        }
        return null;
    },
    path: function() {
        return path.join.apply(this, arguments);
    },
    paths: function() {
        var args = [__dirname];
        for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        return path.join.apply(this, args);
    },
    mkdirsSync: function(dirname) {
        if (fs.existsSync(dirname)) {
            return true;
        } else {
            if (this.mkdirsSync(path.dirname(dirname))) {
                fs.mkdirSync(dirname);
                return true;
            }
        }
    },
    readFileSync: function(filepath) {
        return fs.readFileSync(filepath, 'utf-8');
    },
    writeFileSync: function(filepath, text, overwritten) {
        if(fs.existsSync(filepath)) {
            if (!overwritten) return;
        } else {
            this.mkdirsSync(path.dirname(filepath));
        }
        fs.writeFileSync(filepath, text, { flag: 'w', encoding: 'utf-8' });
    },
    copyFileSync: function(targetpath, sourcepath, overwritten) {
        this.writeFileSync(targetpath, this.readFileSync(sourcepath), overwritten);
    },
    deleteAllSync: function(filepath) {
        if(fs.existsSync(filepath)) {
            if(fs.statSync(filepath).isDirectory()) {
                var files = fs.readdirSync(filepath);
                for (var i in files) {
                    var filename = files[i];
                    var curpath = filepath + '/' + filename;
                    if(fs.statSync(curpath).isDirectory()) {
                        this.deleteAllSync(curpath);
                    } else {
                        fs.unlinkSync(curpath);
                    }
                }
                fs.rmdirSync(filepath);
            } else {
                fs.unlinkSync(filepath);
            }
        }
    }
};
